package cn.hashq.netpostclient.handler.proxy;

import cn.hashq.netpostclient.cache.ConnectionInfo;
import cn.hashq.netpostclient.constant.ProtoConstant;
import cn.hashq.netpostclient.constant.SessionKey;
import cn.hashq.netpostclient.dto.ProtoMsg;
import cn.hashq.netpostclient.handler.BaseHandler;
import cn.hashq.netpostclient.session.ClientSession;
import cn.hashq.netpostclient.util.NettyUtil;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPipeline;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Slf4j
@ChannelHandler.Sharable
public class AuthResponseHandler extends BaseHandler {

    @Resource
    private HeartBeatHandler heartBeatHandler = new HeartBeatHandler();

    @Resource
    private ServerDataRedirectHandler serverDataRedirectHandler = new ServerDataRedirectHandler();

    @Override
    public ProtoMsg.HeadType getHeadType() {
        return ProtoMsg.HeadType.AUTH_RESPONSE;
    }

    @Override
    public void process(ChannelHandlerContext ctx, ProtoMsg.Message msg) {
        ProtoMsg.AuthResponse response = msg.getResponse();
        if (response.getCode() == ProtoConstant.ResultCode.SUCCESS.getCode()) {
            log.info("验证密钥成功");
            ClientSession serverSession = new ClientSession(ctx.channel(), SessionKey.PROXY_SESSION_KEY);
            serverSession.reverseBind();
            ChannelPipeline pipeline = ctx.pipeline();
            pipeline.remove(this);
            pipeline.addAfter("decoder", "heart", heartBeatHandler);
            pipeline.addAfter("decoder", "serverDataRedirect", serverDataRedirectHandler);
        } else {
            log.error("连接失败,密钥错误或客户端为开启");
            log.info("正在重连...");
            NettyUtil.delayConnect();
        }
    }

}
